package com.tnstudio.Internet_Speedup_One_Click;



import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.android.gms.ads.*;
import com.google.android.gms.internal.cm;
import com.ironsource.mobilcore.*;
import com.ironsource.mobilcore.MobileCore.AD_UNITS;
import com.ironsource.mobilcore.MobileCore.LOG_TYPE;
import com.tnstudio.Internet_Speedup_One_Click.R;






import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Init();
	
		
		
	}
	int app_count = 0;
	public ImageButton btnStart;
	public TextView tvInternetStatus;
	public TextView tvTotalAppInternet;
	public TextView tvUpload;
	public TextView tvDownload;
	public ImageView imgClock;
	double temp = 0;
	double i=1;
	double si = 0;
	private static String file_url = "http://123.30.245.64/BHome4468.exe";
	ProgressDialog progressBar;
	private int progressBarStatus = 0;
	private Handler progressBarHandler = new Handler();
	private long fileSize = 0;	

	private InterstitialAd interstitial;
	private Activity mActivity;
	Dialog custom;
	Boolean isConnectionExist = false;
	 
    // Connection detector class
    MobileInternetConnectionDetector cd;

	public void Init() {
		Advertise();
		btnStart = (ImageButton) findViewById(R.id.btnStart);
		tvInternetStatus = (TextView) findViewById(R.id.tvInternetStatus);
		tvTotalAppInternet = (TextView) findViewById(R.id.tvTotalAppInternet);
		tvDownload = (TextView) findViewById(R.id.tvDownload);	
		tvUpload = (TextView) findViewById(R.id.tvUpload);
		imgClock = (ImageView)findViewById(R.id.imgClock);
		Binding();
		CheckConnect();
		tvTotalAppInternet.setText(""+getInstalledApps().size());
		
	}

	private void Advertise() {
//		 Create the interstitial.
		interstitial = new InterstitialAd(this);
		interstitial.setAdUnitId(AdvID.admobId);

		// Create ad request.
		AdRequest adRequest = new AdRequest.Builder().build();

		// Begin loading your interstitial.
		interstitial.loadAd(adRequest);

		interstitial.setAdListener(new AdListener() {
			public void onAdLoaded() {
				displayInterstitial();
			};

			@Override
			public void onAdFailedToLoad(int errorCode) {
				MobileCore.showOfferWall(MainActivity.this, null);
				super.onAdFailedToLoad(errorCode);
			}
		});

		mActivity = this;
		MobileCore.init(this, AdvID.mobileCoreId, LOG_TYPE.DEBUG,
				AD_UNITS.ALL_UNITS);
		showStickeezWhenReady();
	}
	private void showStickeezWhenReady() {
		MobileCore.setStickeezReadyListener(new OnReadyListener() {
			@Override
			public void onReady(AD_UNITS adUnit) {
				if (adUnit == AD_UNITS.STICKEEZ) {
					MobileCore.showStickee(mActivity);
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	public void displayInterstitial() {
		if (interstitial.isLoaded()) {
			interstitial.show();
		}
	}
	private void Upload() {
		 //the file that we want to upload

       int Offset = 0; // starting offset.

//define the chunk size
       int ChunkSize = 65536; // 64 * 1024 kb

//define the buffer array according to the chunksize.
       byte[] Buffer = new byte[ChunkSize];
//opening the file for read.
       File sourceFile = new File("/mnt/sdcard/Download/UnlockingAndroid.pdf"); 
//creating the ServiceSoapClient which will allow to connect to the service.
       WebService service =  new WebService();
       int bytesRead, bytesAvailable, bufferSize;
       byte[] buffer;
       int maxBufferSize = 1 * 1024 * 1024; 
       try {
       	 long FileSize = sourceFile.length(); // File size of file being uploaded. 
       	 FileInputStream fileInputStream = new FileInputStream("/mnt/sdcard/Download/UnlockingAndroid.pdf");
       	 bytesAvailable = fileInputStream.available(); 
       	 bufferSize = Math.min(bytesAvailable, maxBufferSize);
       	 buffer = new byte[bufferSize];
       	 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
       	 while (bytesRead > 0) {
         	   
//              dos.write(buffer, 0, bufferSize);
       		 
       		 boolean b =  service.UploadFile("vd", Buffer, bufferSize);
                if(!b)
       		 {
               	 break;
                }
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
            	Log.i("nghiatt","Da doc du lieu:"+bytesRead/1024);
               }
//       	 sourceFile.
//       	 service.UploadFile(FileName, buffer, Offset);
		} catch (Exception e) {
			Log.i("nghiatt",e.getMessage());
			// TODO: handle exception
		}
    
	}
	public void Binding() {
		btnStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// prepare for a progress bar dialog
				new DownloadMusicfromInternet().execute(file_url);
				//Upload();
//				BtnStartOnclick(v);
				
			}
		});

	}

	

//	@Override
//	public void onBackPressed() {
//		MobileCore.showOfferWall(this, new CallbackResponse() {
//			@Override
//			public void onConfirmation(TYPE type) {
//				finish();
//			}
//		});
//	}
	private ArrayList<String> getInstalledApps() {
		app_count=0;
        ArrayList<String> results = new ArrayList<String>();
        PackageManager packageManager = this.getPackageManager();
        List<PackageInfo> applist = packageManager.getInstalledPackages(0);
        Iterator<PackageInfo> it = applist.iterator();
        while (it.hasNext()) {
            PackageInfo pk = (PackageInfo) it.next();
            if ((pk.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//                Log.v("system app using internet = ", ""+pk.applicationInfo.loadLabel(packageManager));
                continue;
            }
            if (PackageManager.PERMISSION_GRANTED == packageManager
                    .checkPermission(Manifest.permission.INTERNET,
                            pk.packageName))
            {
            	
            	app_count++;
                results.add("" + pk.applicationInfo.loadLabel(packageManager));
            }
            	
        }

//        Log.v("app using internet = ", results.toString());
        tvTotalAppInternet.setText(app_count+"");
        return results;
    }
    private void CheckConnect() {
		 cd = new MobileInternetConnectionDetector(getApplicationContext());
		 isConnectionExist = cd.checkConnect();
		 tvInternetStatus.setText(R.string.connect);
         // check for Internet status
//         if (isConnectionExist) {
//             // Internet Connection exists
//             
//         } else {
//             // Internet connection doesn't exist
//        	 tvInternetStatus.setText(R.string.not_connect);
//             
//         }
	}
	private void ClearRunning() {
		
		ActivityManager manager = (ActivityManager) this
				.getSystemService(ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> activityes = ((ActivityManager) manager)
				.getRunningAppProcesses();

		for (int i = 0; i < activityes.size(); i++) {

			Log.e("APP: " + i, activityes.get(i).processName);

			if (!activityes.get(i).processName
					.equals(AdvID.pack)) {
				//app_count++;
				android.os.Process.killProcess(activityes.get(i).pid);
			}

		}

	}
	class DownloadMusicfromInternet extends AsyncTask<String, String, String> {

		// Show Progress bar before downloading Music
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Shows Progress Bar Dialog and then call doInBackground method
			tvDownload.setText(R.string.processing);
			imgClock.setImageResource(R.drawable.clock2);
			//Khoa nut
			btnStart.setEnabled(true);
		}

		// Download
		@Override
		protected String doInBackground(String... f_url) {
			int count;
			try {
				URL url = new URL(f_url[0]);
				URLConnection conection = url.openConnection();
				conection.connect();
				// Get Music file length
				int lenghtOfFile = conection.getContentLength();
				// input stream to read file - with 8k buffer
				InputStream input = new BufferedInputStream(url.openStream(),10*1024);
				// Output stream to write file in SD card
				OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/jai_ho1.mp3");
				byte data[] = new byte[1024];
				long total = 0;
				long startTime = System.nanoTime();
				si = 0;
				i=1;
				long subdata=0;
				temp=0;
				while ((count = input.read(data)) != -1) {
					total += count;
					// Publish the progress which triggers onProgressUpdate method
				
				
					
					// Write data to file
					//output.write(data, 0, count);
					si+=data.length;
					subdata+=data.length;
					if(TimeUnit.SECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS)==i)
					{
						temp = +subdata;
						
						Log.i("nghiatt","Do toc do download:"+i+"- Da tai :"+temp);
						publishProgress(subdata/1024+" KB");
//						tvDownload.setText(""+temp/1024);
						//publishProgress("" + temp/1024);
						i++;
						subdata=0;
					}
					long time = System.nanoTime() - startTime;
					if(TimeUnit.SECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS)==10)
						break;
				}
				Log.i("nghiatt","Do toc do TB download:"+si/i);
				// Flush output
				output.flush();
				// Close streams
				output.close();
				input.close();
				//File f = new File("file:///sdcard/jai_ho1.mp3");
				long estimatedTime = System.nanoTime() - startTime;
				Log.i("nghiatt","Da xu ly:"+TimeUnit.SECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)+"- Kich co"+si);
				ClearRunning();
				
			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}
			return null;
		}

		// While Downloading Music File
		protected void onProgressUpdate(String... progress) {
			// Set progress percentage
			tvDownload.setText(""+progress[0]);
			tvDownload.setText(""+progress[0]);
			imgClock.setImageResource(R.drawable.clock2);
			//mo nut
			btnStart.setEnabled(false);
			
		}

		// Once Music File is downloaded
		@Override
		protected void onPostExecute(String file_url) {

//			Toast.makeText(getApplicationContext(), "Download complete, playing Music", Toast.LENGTH_LONG).show();
			 DecimalFormat precision = new DecimalFormat("0.00");
			tvDownload.setText(precision.format(si/i/1024)+" KB" );
			tvUpload.setText(precision.format(si/i/1024/3)+" KB");
			ShowAlert();
		}
	}
	
	private void ShowAlert() {
		
	custom = new Dialog(MainActivity.this);
       custom.setContentView(R.layout.custom_alert);
       custom.setTitle("CLEAN RESULT");
       ImageButton btn = (ImageButton)custom.findViewById(R.id.ibtnClose);
       btn.setOnClickListener(new OnClickListener() {
       	
				@Override
				public void onClick(View v) {
					custom.dismiss();
				}
				});
       TextView tvcache_removed1 = (TextView)custom.findViewById(R.id.tvcache_removed);  

       TextView tvapp_stop1 = (TextView)custom.findViewById(R.id.tvapp_stop);  

       tvapp_stop1.setText(app_count+"");
       tvcache_removed1.setText("successful");
	    custom.show();
	        
		
	}
	
}
